<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="100%">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="120px">
      <el-row>
      <el-form-item label="收款单据编号" prop="code">
        <el-input v-model="dataForm.code" placeholder="单据编号">
          <el-button slot="append" icon="el-icon-search" @click="getLastCode(dataForm)"></el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="单据日期" prop="orderDate">
        <el-date-picker type="date" v-model="dataForm.orderDate" @on-change="orderDateChange"
                        placeholder="单据日期" :editable="false" style="width: 100%"></el-date-picker>
      </el-form-item>

      <el-form-item label="客户" prop="clientName">
        <!--      <el-input v-model="dataForm.clientName" placeholder="租户ID"></el-input>-->
        <el-autocomplete v-model="dataForm.clientName" style="width: 100%"
                         :fetch-suggestions="querySearchClient" placeholder="请输入客户名称"
                         popper-class="select-option"
                         @select="handleClientSelect"></el-autocomplete>
      </el-form-item>
      </el-row>
      <el-row>
      <el-form-item label="账户" prop="accountName">
        <el-autocomplete v-model="dataForm.accountName" style="width: 100%"
                         :fetch-suggestions="querySearchAccount" placeholder="请输入账户名称"
                         popper-class="select-option"
                         @select="handleAccountSelect"></el-autocomplete>
      </el-form-item>
      <el-form-item label="类别" size="mini" prop="type">
        <el-radio-group v-model="dataForm.type">
          <el-radio :label="0">收入</el-radio>
          <el-radio :label="1">支出</el-radio>
        </el-radio-group>
      </el-form-item>
      </el-row>
      <el-row>
      <el-form-item>
        <el-button v-if="isAuth('funds:dailydetail:save')" type="primary" @click="addRow">新增</el-button>
        <el-button v-if="isAuth('funds:dailydetail:delete')" type="danger" @click="deleteHandle()"
                   :disabled="dataListSelections.length <= 0">批量删除</el-button>
      </el-form-item>

        <el-table
          :data="dataList"
          border
          v-loading="dataListLoading"
          :summary-method="getSummaries"
          show-summary
          @selection-change="selectionChangeHandle"
          style="width: 100%;">
          <el-table-column
            type="selection"
            header-align="center"
            align="center"
            width="50">
          </el-table-column>
          <el-table-column
            prop="typeName"
            header-align="center"
            align="center"
            label="类别">
            <template slot-scope="scope">
              <el-autocomplete v-if="scope.row.status" v-model="scope.row.typeName"
                               :fetch-suggestions="queryTypeSearch" placeholder="请输入内容"
                               @select="handleTypeSelect($event, scope.row)"
                               popper-class="select-option" width="100%"
              ></el-autocomplete>
              <span v-else>{{scope.row.typeName}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="amount"
            header-align="center"
            align="center"
            label="金额(元)">
            <template slot-scope="scope">
              <!--          <el-input v-if="scope.row.status" v-model="scope.row.salesAmount"-->
              <!--                    ></el-input>-->
              <el-input v-if="scope.row.status" v-model="scope.row.amount"
                        @keyup.native="scope.row.amount = oninputMoney(scope.row.amount)"></el-input>
              <span v-else>{{scope.row.amount}}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="remark"
            header-align="center"
            align="center"
            label="备注">
            <template slot-scope="scope">
              <el-input v-if="scope.row.status" v-model="scope.row.remark"></el-input>
              <span v-else>{{scope.row.remark}}</span>
            </template>
          </el-table-column>

          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            width="150"
            label="操作">
            <template slot-scope="scope">
              <el-button class="el-icon-edit" type="primary" :disabled="scope.row.status==1"
                         size="small" circle @click.native.prevent="editRow(scope.row)"></el-button>
              <el-button class="el-icon-delete" type="danger"
                         size="small" circle @click.native.prevent="deleteRow(scope.$index, dataList)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    activated () {
      // this.getDataList()
      this.getDailyDetailsByHeadId(this.dataForm.headerId)
    },
    data () {
      return {
        visible: false,
        clientIdForSearch: '',
        amount: 0,
        dataList: [],
        delList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        dataForm: {
          id: 0,
          status: 0,
          deleted: '',
          createUserId: '',
          createTime: '',
          tenantId: '',
          code: '',
          orderDate: new Date(),
          clientId: '',
          clientName: '',
          accountId: '',
          accountName: '',
          createUser: '',
          type: 0,
          remark: '',
          amount: '',
          typeName: '',
          headerId: this.id
        },
        formDto: {
          dailyDetailList: [],
          deleteDailyDetailList: []
        },
        dataRule: {
          code: [
            {required: true, message: '单据编号不能为空', trigger: 'blur'}
          ],
          orderDate: [
            {required: true, message: '单据日期不能为空', trigger: 'blur'}
          ],
          type: [
            {required: true, message: '类别不能为空', trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.dataList = []
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/funds/dailyheader/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.status = data.dailyHeader.status
                this.dataForm.deleted = data.dailyHeader.deleted
                this.dataForm.createUserId = data.dailyHeader.createUserId
                this.dataForm.createTime = data.dailyHeader.createTime
                this.dataForm.tenantId = data.dailyHeader.tenantId
                this.dataForm.code = data.dailyHeader.code
                this.dataForm.orderDate = data.dailyHeader.orderDate
                this.dataForm.clientId = data.dailyHeader.clientId
                this.dataForm.accountId = data.dailyHeader.accountId
                this.dataForm.clientName = data.dailyHeader.clientName
                this.dataForm.accountName = data.dailyHeader.accountName
                this.dataForm.createUser = data.dailyHeader.createUser
                this.dataForm.type = data.dailyHeader.type

                this.getInitData()

                // this.$refs.receiptDetailsData.getReceiptDetailsByHeadId(this.dataForm.id)
                this.getDailyDetailsByHeadId(this.dataForm.id)
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        // 订单明细
        this.formDto.dailyDetailList = this.dataList
        this.formDto.deleteDailyDetailList = this.delList

        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/funds/dailyheader/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'status': this.dataForm.status,
                'deleted': this.dataForm.deleted,
                'createUserId': this.dataForm.createUserId,
                'createTime': this.dataForm.createTime,
                'tenantId': this.dataForm.tenantId,
                'code': this.dataForm.code,
                'orderDate': this.dataForm.orderDate,
                'createUser': this.dataForm.createUser,
                'type': this.dataForm.type,

                'clientId': this.dataForm.clientId,
                'clientName': this.dataForm.clientName,
                'accountId': this.dataForm.accountId,
                'accountName': this.dataForm.accountName,

                'dailyDetailList': this.formDto.dailyDetailList,
                'deleteDailyDetailList': this.formDto.deleteDailyDetailList
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 客户 远程搜索
      // queryString 为在框中输入的值
      // callback 回调函数,将处理好的数据推回
      querySearchClient (queryString, callback) {
        this.s_girard = queryString === '' || queryString === null ? 'undefined' : queryString
        this.loading = true
        this.$http({
          url: this.$http.adornUrl(`/sto/client/listClients/${this.s_girard}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.clients = data.clientsMap.clientNameDtoList
          } else {
            this.clients = []
          }
        })
        // callback(this.clients)
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          callback(this.clients)
        }, 500)
      },
      handleClientSelect (item) {
        console.log(item)
        // do something
        this.dataForm.clientId = item.clientId
        this.clientIdForSearch = item.clientId
        this.dataForm.clientName = item.value
      },
      // 账户 远程搜索
      // queryString 为在框中输入的值
      // callback 回调函数,将处理好的数据推回
      querySearchAccount (queryString, callback) {
        this.s_girard = queryString === '' || queryString === null ? 'undefined' : queryString
        this.loading = true
        this.$http({
          url: this.$http.adornUrl(`/sto/account/listAccounts/${this.s_girard}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.accounts = data.accountsMap.accountNameDtoList
          } else {
            this.accounts = []
          }
        })
        // callback(this.clients)
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          callback(this.accounts)
        }, 500)
      },
      handleAccountSelect (item) {
        console.log(item)
        // do something
        this.dataForm.accountId = item.accountId
        this.dataForm.accountName = item.accountName
      },
      // 合计
      getSummaries (param) {
        const {columns, data} = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 1) {
            sums[index] = '合计'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          // 金额(元)
          if (column.property === 'amount') {
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              sums[index] += ''
            } else {
              sums[index] = ''
            }

            sums[index] = parseFloat(sums[index]).toFixed(2)

            this.amount = sums[index]
          }
        })

        return sums
      },
      // 获取最新的编号
      getLastCode (dataForm) {
        this.$http({
          url: this.$http.adornUrl(`/funds/dailyheader/getLastCode`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            dataForm.code = data.lastCode
          } else {
            dataForm.code = ''
          }
        })
      },
      getInitData () {
        // 单据日期，默认显示今天
        this.dataForm.orderDate = new Date()
      },
      orderDateChange (data) {
        this.dataForm.orderDate = new Date(data)
      },
      // 新增一行
      addRow () {
        this.dataList.push({
          typeName: '',
          amount: 0,
          status: 1
        })
      },
      // 删除该行
      deleteRow (index, rows) {
        this.delList.push(rows[index].id)
        rows.splice(index, 1)
      },
      editRow (row) {
        row.status = 1
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/funds/dailydetail/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      oninputMoney (num) {
        let str = num
        let len1 = str.substr(0, 1)
        let len2 = str.substr(1, 1)
        // 如果第一位是0，第二位不是点，就用数字把点替换掉
        if (str.length > 1 && len1 === 0 && len2 !== '.') {
          str = str.substr(1, 1)
        }
        // 第一位不能是.
        if (len1 === '.') {
          str = ''
        }
        // 限制只能输入一个小数点
        if (str.indexOf('.') !== -1) {
          let str_ = str.substr(str.indexOf('.') + 1)
          if (str_.indexOf('.') !== -1) {
            str = str.substr(0, str.indexOf('.') + str_.indexOf('.') + 1)
          }
        }
        // 正则替换
        str = str.replace(/[^\d.]/g, '') // 保留数字和小数点
        str = str.replace(/\.\d\d\d$/, '') // 小数点后只能输两位
        return str
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 获取数据列表
      getDailyDetailsByHeadId (id) {
        this.dataForm.headerId = id || 0
        this.dataListLoading = true
        this.delList = []
        this.$http({
          url: this.$http.adornUrl('/funds/dailydetail/listAllByHeadId'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'headId': id
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 类型 远程搜索
      // queryString 为在框中输入的值
      // callback 回调函数,将处理好的数据推回
      queryTypeSearch (queryString, callback) {
        this.s_girard = queryString === '' || queryString === null ? 'undefined' : queryString
        this.loading = true
        this.$http({
          url: this.$http.adornUrl(`/funds/dailydetail/listTypes/${this.s_girard}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.accounts = data.typeMap.typesList
          } else {
            this.accounts = []
          }
        })
        // callback(this.clients)
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          callback(this.accounts)
        }, 500)
      },
      handleTypeSelect (item) {
        console.log(item)
        // do something
        this.dataForm.accountId = item.accountId
        this.dataForm.accountName = item.accountName
      }
    }
  }
</script>
